import sys
import json

from PySide6 import QtCore
from PySide6.QtGui import QImage, QColor
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication, QMainWindow
from MainWindow import Ui_MainWindow

tick = QImage('tick.png')
color = QColor('red')

class TodoModel(QtCore.QAbstractListModel):
    def __init__(self, todos=None):
        super().__init__()
        self.todos = todos or []

    def data(self, index, role):
        if role == Qt.DisplayRole:
            status, text = self.todos[index.row()]
            return text
        
        if role == Qt.DecorationRole:
            status, text = self.todos[index.row()]
            if status:
                return color
    
    def rowCount(self, index):
        return len(self.todos)
    
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.model = TodoModel()
        self.load()
        self.todoView.setModel(self.model)

        self.addButton.pressed.connect(self.add)
        self.deleteButton.pressed.connect(self.delete)
        self.completeButton.pressed.connect(self.complete)

    def add(self):
        text = self.todoEdit.text()
        text = text.strip()

        if text:
            self.model.todos.append({False, text})
            self.model.layoutChanged.emit()
            self.todoEdit.setText("")
    def delete(self):
        indexes = self.todoView.selectedIndexes()
        if indexes:
            index = indexes[0]

            del self.model.todos[index.row()]
            self.model.layoutChanged.emit()
            self.todoView.clearSelection()

    def complete(self):
        indexes = self.todoView.selectedIndexes()
        if indexes:
            index = indexes[0]
            row = index.row()
            status, text = self.model.todos[row]
            self.model.todos[row] = (True, text)
            self.model.dataChanged.emit(index, index)
            self.todoView.clearSelection()
            self.save()

    def load(self):
        try:
            with open('data.json', 'r') as f:
                self.model.todos = json.load(f)
        except Exception:
            pass
    
    def save(self):
        with open('data.json', 'w') as f:
            data = json.dump(self.model.todos, f)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()